﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections.Specialized;

namespace CustomForms
{
    public partial class MembershipDetails : Form
    {
        public string ConnectionString { get; set; }

        public bool IsWindowsCredentials { get; set; }
        public string DatabaseServer { get; set; }
        public string DatabaseName { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }


        public MembershipDetails()
        {
            InitializeComponent();
        }

        private void rbSQLAuthentication_CheckedChanged(object sender, EventArgs e)
        {
            txbPassword.Enabled = rbSQLAuthentication.Checked;
            txbUsername.Enabled = rbSQLAuthentication.Checked;


        }

        private void btnTestConnection_Click(object sender, EventArgs e)
        {
            

            Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;

            if (false == InitializeConnectionString()) return;

            ValidateConnection(false);

            Cursor.Current = System.Windows.Forms.Cursors.Default;
            
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
            if (false == InitializeConnectionString()) return;
            ValidateConnection(true);

            Cursor.Current = System.Windows.Forms.Cursors.Default;


            string serverName = txbServerName.Text;
            //MessageBox.Show(serverName, "server");

            string dbName = cmbDatabase.Text;
           // MessageBox.Show(dbName, "db");

            DatabaseName = dbName;
            DatabaseServer = serverName;

            if (rbSQLAuthentication.Checked)
            {
                //MessageBox.Show(txbUsername.Text, "user name");
               // MessageBox.Show(txbPassword.Text, "pasword");
                IsWindowsCredentials = false;
                UserName = txbUsername.Text;
                Password = txbPassword.Text;
            }
            else
            {
                string currentUserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
                //MessageBox.Show(currentUserName, "windows account");
                IsWindowsCredentials = true;
            }

            this.Close();
        }

        
        private void txbServerName_Leave(object sender, EventArgs e)
        {
            if (cmbDatabase.Items.Count > 0) return;

            if (false == InitializeConnectionString()) return;

          
            List<KeyValuePair<string, string>> databasesCollection = GetAllDatabases(txbServerName.Text, ConnectionString);
            cmbDatabase.DataSource = null;
            cmbDatabase.Items.Clear();

            // Bind the combobox
            cmbDatabase.DataSource = new BindingSource(databasesCollection, null);
            cmbDatabase.DisplayMember = "Value";
            cmbDatabase.ValueMember = "Key";

        }


        #region helpers
        private void ValidateConnection(bool subsideSuccessMsg)
        {
            DbUtils.ConnectionString = ConnectionString;

            bool result = DbUtils.TestConnection();

            if (result)
            {
                if (false == subsideSuccessMsg)
                    MessageBox.Show("Connection to the specified server is successful.", "Connection test", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
               
                 MessageBox.Show("Connection to the specified server is not successful.", "Connection test", MessageBoxButtons.OK, MessageBoxIcon.Error);
                 cmbDatabase.DataSource = null;
                 cmbDatabase.Items.Clear();

            }
        }
        private bool InitializeConnectionString()
        {
            if (String.IsNullOrEmpty(txbServerName.Text))
            {
                MessageBox.Show("Enter value for 'Server:'.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                ConnectionString = String.Empty;
                return false;
            }

            if (rbWindowsAuthentication.Checked)
                ConnectionString = String.Format("Data Source={0}; Integrated Security=True; Database=master", txbServerName.Text);
            else
            {
                if (String.IsNullOrEmpty(txbUsername.Text) || String.IsNullOrEmpty(txbPassword.Text))
                {
                    MessageBox.Show("Enter value for 'User name:' and 'Password:' .", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    ConnectionString = String.Empty;
                    return false;
                }
                ConnectionString = String.Format("Data Source={0}; Integrated Security=false; Database=master;User ID={1};Password={2};", txbServerName.Text, txbUsername.Text, txbPassword.Text);
            }

            return true;

            
        }
        private List<KeyValuePair<string, string>> GetAllDatabases(string servername, string connectionString)
        {
            
            List<KeyValuePair<string, string>> collection = new List<KeyValuePair<string, string>>();

            DbUtils.ConnectionString = connectionString;
            try
            {
                DataSet dbs = DbUtils.ExecuteDataSet("sp_databases");
                if (dbs == null)
                {
                    return collection;
                }
                DataTable dt = dbs.Tables[0];
                foreach (DataRow row in dt.Rows)
                {
                    string database = row["DATABASE_NAME"].ToString();
                    collection.Add(new KeyValuePair<string, string>(database, database));
                    
                }
            }
            catch
            { 
                
            }

            return collection;
        }
        #endregion

        private void rbWindowsAuthentication_CheckedChanged(object sender, EventArgs e)
        {
            txbPassword.Text = String.Empty;
            txbUsername.Text = String.Empty;
        }
    }
}
